<?php
namespace app\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Model\BannerModel;
use App\Model\GoldBeanModel;
use App\Model\PkRecordModel;
use App\Model\PkRelModel;
use APP\Model\WebUserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\ApiMainController;
use App\Model\RelfriendModel;
use Illuminate\Support\Facades\DB;
use App\Model\GoldRecordModel;

class MainController extends ApiMainController
{
    //主页接口
    public function index()
    {
        if ($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }

        $user_data = WebUserModel::where('iUUID', $this->uuid)->first();
        $mainArr = array();

        //当前用户金豆
        $now_gold_bean = GoldBeanModel::select('iNowGoldBean')->where('iUserId', $user_data->iSeqId)->first();
        $gold_bean_num = 0;
        if (!empty($now_gold_bean) && $now_gold_bean->iNowGoldBean > 0) {
            $gold_bean_num = $now_gold_bean->iNowGoldBean;
        }

        //几天未登录
        $pkrecord = PkRecordModel::whereRaw("iUserId={$this->userId} and iOpponentId!=0 and iStatus=2 and dtStartTime!=''")
            ->orWhereRaw("iOpponentId={$this->userId} and iOpponentId!=0 and iStatus=2 and dtStartTime!=''")
            ->orderBy("dtStartTime", "DESC")
            ->select(DB::raw("DATE_FORMAT(dtStartTime,'%Y-%m-%d') as startTime"))
            ->first();
        $time_info=0;
        //var_dump($pkrecord->startTime);
        if(!empty($pkrecord->startTime)){
            $time_info = (strtotime(date("Y-m-d")) - strtotime($pkrecord->startTime))/ (60 * 60 * 24);
        }

        //banner
        $banner = BannerModel::select('banner')
            ->orderBy('iSeqId','DESC')
            ->limit(10)
            ->get()
            ->toArray();
        if($banner){
           foreach ($banner as $list){
               $content[] = $list['banner'];
           }
        }
        $mainArr['pkday'] = empty($time_info) ?  0 : $time_info;
        $mainArr['gold_bean_num'] =  $gold_bean_num;
        $mainArr['type'] =  empty($user_data) ?  '' : $user_data->type;
        /*$mainArr['banner'] = array(
            "刚刚 洛枫 消耗了3500 金币兑换了 可乐，还不快去赢金币换奖；",
            "刚刚 洛枫 赢得了一场比赛，获得了 5000 金币，快去发起挑战吧",
            "刚刚 Qatar94 消耗了5000 金币兑换了 可乐，还不快去赢金币换奖；",
            "刚刚 Qatar94 赢得了一场比赛，获得了 5000 金币，快去发起挑战吧",
            "刚刚 console 消耗了4000 金币兑换了 可乐，还不快去赢金币换奖；",
            "刚刚 console 赢得了一场比赛，获得了 5000 金币，快去发起挑战吧",
            "刚刚 诺克™ 消耗了7000金币兑换了 可乐，还不快去赢金币换奖；",
            "刚刚 诺克™ 赢得了一场比赛，获得了 5000 金币，快去发起挑战吧",
            "刚刚 康浩然 消耗了6500 金币兑换了 可乐，还不快去赢金币换奖；",
            "刚刚 康浩然 赢得了一场比赛，获得了 5000 金币，快去发起挑战吧",
        );*/
        $mainArr['banner'] = !empty($content) ? $content : [];


        return response()->json(array(
            'code' => 200,
            'message' => '查询成功！！',
            'data' => array(
                'uuid' => $this->uuid,
                'list' => $mainArr,
            ),
        ));


    }

    public function details(Request $request)
    {
        if ($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        //1 老对手 2 好友人气榜 3 好友财富榜 4 球厅人气榜 5 球厅财富榜
        $type = $request->input('type') ? intval($request->input('type')) : '';
        $page = $request->input('page') ? intval($request->input('page')) : 1;
        $limit = $request->input('limit') ? intval($request->input('limit')) : 10;//默认显示10

        if (!isset($type) || empty($type)) {
            return response()->json(array('code' => 400, 'message' => '类型不能为空', 'data' => []));
        }
        switch ($type) {
            case 1:
                //老对手获取
                $users = RelfriendModel::where(array("master_user_id" => $this->userId))
                    ->leftJoin('webuser', 'relfriend.user_id', '=', 'webuser.iSeqId')
                    ->orderBy("relfriend.iAllPk", "DESC")
                    ->select("relfriend.*", "webuser.sUserImage", "webuser.sUserName","webuser.iUUID")
                   // ->where('relfriend.iStaues',1)
                    ->paginate($limit)
                    ->toArray();
                //var_dump($users['data']);
                foreach($users['data'] as &$v){
                    $v['sUserName']=htmlspecialchars(urldecode($v['sUserName']));
                }
                return response()->json(array(
                    'code' => 200,
                    'message' => "查询成功",
                    "date" => array(
                        "uuid" => $this->uuid,
                        "total" => $users['total'],
                        "current_page" => $users['current_page'],
                        "list" => $users['data'],
                    )
                ));
                break;
            case 2:
                //好友人气榜
                //step1 查出我的好友
                $arr1 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();

                $arr2 = array_map('array_shift', $arr1);
                $arr2[] = $this->userId;
                $users = RelfriendModel::whereIn('master_user_id', $arr2)
                    ->leftJoin('webuser', 'relfriend.master_user_id', '=', 'webuser.iSeqId')
                    ->leftJoin('goldbean', 'relfriend.master_user_id', '=', 'goldbean.iUserId')
                    ->groupBy('master_user_id')
                    ->orderBy("countfriend", "DESC")
                    ->orderBy("master_user_id", "DESC")
                    ->select(DB::raw('count(master_user_id) as countfriend, master_user_id,tb_webuser.sUserImage,tb_webuser.sUserName,tb_webuser.iUUID,tb_goldbean.iNowGoldBean'))
                    ->paginate($limit)
                    ->toArray();
                //var_dump($users);
                foreach($users['data'] as &$v){
                    $v['sUserName']=htmlspecialchars(urldecode($v['sUserName']));
                }
                if(count($users['data'])==0){
                    $user=WebUserModel::where("webuser.iSeqId",$this->userId)
                        ->leftJoin('goldbean', 'webuser.iSeqId', '=', 'goldbean.iUserId')
                        ->select(DB::raw("tb_webuser.*,tb_goldbean.iNowGoldBean"))
                        ->get()->toArray();
                    if(!empty($user)){
                        $user[0]['sUserName']=htmlspecialchars(urldecode($user[0]['sUserName']));
                        $user[0]['countfriend']=0;
                    }
                    $users['data']=$user;
                    $users['total']=1;
                }
                return response()->json(array(
                    'code' => 200,
                    'message' => "查询成功",
                    "date" => array(
                        "uuid" => $this->uuid,
                        "total" => $users['total'],
                        "current_page" => $users['current_page'],
                        "list" => $users['data'],
                    )
                ));
                break;
            case 3:
                //好友财富榜
                //step1 查出我的好友
                $arr1 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();

                $arr2 = array_map('array_shift', $arr1);
                $arr2[] = $this->userId;
                $users = GoldBeanModel::whereIn('iUserId', $arr2)
                    ->leftJoin('webuser', 'goldbean.iUserId', '=', 'webuser.iSeqId')
                    ->orderBy("iNowGoldBean", "DESC")
                    ->orderBy("iUserId", "DESC")
                    ->select(DB::raw('iUserId,iNowGoldBean,tb_webuser.sUserImage,tb_webuser.sUserName,tb_webuser.iUUID'))
                    ->paginate($limit)
                    ->toArray();
                foreach($users['data'] as &$v){
                    $v['sUserName']=htmlspecialchars(urldecode($v['sUserName']));
                }
                return response()->json(array(
                    'code' => 200,
                    'message' => "查询成功",
                    "date" => array(
                        "uuid" => $this->uuid,
                        "total" => $users['total'],
                        "current_page" => $users['current_page'],
                        "list" => $users['data'],
                    )
                ));
                break;
            case 4:
                //球厅人气榜
               /* $users = RelfriendModel::leftJoin('webuser', 'relfriend.master_user_id', '=', 'webuser.iSeqId')
                    ->leftJoin('goldbean', 'relfriend.master_user_id', '=', 'goldbean.iUserId')
                    ->groupBy('master_user_id')
                    ->orderBy("countfriend", "DESC")
                    ->select(DB::raw('count(master_user_id) as countfriend, master_user_id,tb_webuser.sUserImage,tb_webuser.sUserName,tb_goldbean.iNowGoldBean'))
                    ->paginate($limit)
                    ->toArray();*/
                $users = WebUserModel::leftJoin('relfriend', 'relfriend.master_user_id', '=', 'webuser.iSeqId')
                    ->groupBy('webuser.iSeqId')
                    ->orderBy("countfriend", "DESC")
                    ->orderBy("webuser.iSeqId", "DESC")
                    ->select(DB::raw('tb_webuser.iSeqId,count(master_user_id) as countfriend, master_user_id,tb_webuser.sUserImage,tb_webuser.sUserName'))
                    ->paginate($limit)
                    ->toArray();
                foreach($users['data'] as &$v){
                    $v['sUserName']=htmlspecialchars(urldecode($v['sUserName'])) ;
                }

                //
                return response()->json(array(
                    'code' => 200,
                    'message' => "查询成功",
                    "date" => array(
                        "uuid" => $this->uuid,
                        "total" => $users['total'],
                        "current_page" => $users['current_page'],
                        "list" => $users['data'],
                    )
                ));
                break;
            case 5:
                //球厅财富榜
                $users = GoldBeanModel::leftJoin('webuser', 'goldbean.iUserId', '=', 'webuser.iSeqId')
                    ->orderBy("iNowGoldBean", "DESC")
                    ->orderBy("iUserId", "DESC")
                    ->select(DB::raw('iUserId,iNowGoldBean,tb_webuser.sUserImage,tb_webuser.sUserName'))
                    ->paginate($limit)
                    ->toArray();
                foreach($users['data'] as &$v){
                    $v['sUserName']=mb_convert_encoding(urldecode($v['sUserName']), "UTF-8","UTF-8");
                    //$v['sUserName']=nl2br(urldecode($v['sUserName'])));
                }
                return response()->json(array(
                    'code' => 200,
                    'message' => "查询成功",
                    "date" => array(
                        "uuid" => $this->uuid,
                        "total" => $users['total'],
                        "current_page" => $users['current_page'],
                        "list" => $users['data'],
                    )
                ));
                break;
            default;
                return response()->json(array('code' => 400, 'message' => '不能为空', 'data' => []));
                break;
        }
    }

    //我的接口
    public function main(Request $request){
        if ($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        if(strlen($this->uuid) < 32){
            $user_data = WebUserModel::where('iUUID','like',$this->uuid."%")->first();
        }else{
            $user_data = WebUserModel::where('iUUID',$this->uuid)->first();
        }

        //人气
        $arr1 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr1 = array_map('array_shift', $arr1);
        $arr1[] = $this->userId;
        $user1 = RelfriendModel::whereIn('master_user_id', $arr1)
            ->groupBy('master_user_id')
            ->orderBy("countfriend", "DESC")
            ->select(DB::raw('count(master_user_id) as countfriend,master_user_id'))
            ->get()
            ->toArray();
        $paiming=0;
        $renqi=0;
        foreach($user1 as $key=>$value){
            if($value['master_user_id']==$this->userId){
                $paiming=$key+1;
                $renqi=$value['countfriend'];
            }
        }
        //财富
        $arr2 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr2 = array_map('array_shift', $arr2);
        $arr2[] = $this->userId;
        $user2 = GoldBeanModel::whereIn('iUserId', $arr2)
            ->orderBy("iNowGoldBean", "DESC")
            ->get()
            ->toArray();
        $caifupaiming=0;
        $caifu=0;
        foreach($user2 as $key=>$value){
            if($value['iUserId']==$this->userId){
                $caifupaiming=$key+1;
                $caifu=$value['iNowGoldBean'];
            }
        }
        //赢币
        $arr3 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr3 = array_map('array_shift', $arr3);
        $arr3[] = $this->userId;
        $users3 = GoldRecordModel::whereIn('iUserId', $arr3)
            ->where("iConsumeType",'<',3)
            ->groupBy('iUserId')
            ->orderBy("sumgold", "DESC")
            ->select(DB::raw('sum(iGoldBeanConsume) as sumgold ,iUserId'))
            ->get()
            ->toArray();
        $yingbipaiming=0;
        $yingbi=0;
        foreach($users3 as $key=>$value){
            if($value['iUserId']==$this->userId){
                $yingbipaiming=$key+1;
                $yingbi=$value['sumgold'];
            }
        }

        //场次
        $arr4 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr4= array_map('array_shift', $arr4);
        $arr4[] = $this->userId;
        $users4 = WebUserModel::whereIn('iSeqId', $arr4)
            ->orderBy("iAllPk","DESC")
            ->get()
            ->toArray();
        $changcipaiming=0;
        $changci=0;
        foreach($users4 as $key=>$value){
            if($value['iSeqId']==$this->userId){
                $changcipaiming=$key+1;
                $changci=$value['iAllPk'];
            }
        }

        //平均用时
        $arr5 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr5= array_map('array_shift', $arr5);
        $arr5[] = $this->userId;
        //print_r($arr5);
        $users5 = WebUserModel::whereIn('iSeqId', $arr4)
            ->orderBy("avg", "DESC")
            ->select(DB::raw('iAllTime/iAll as avg ,iSeqId'))
            ->get()
            ->toArray();
        $pingjunpaiming=0;
        $pingjun=0;
        foreach($users5 as $key=> $value){
            if( $value['iSeqId'] == $this->userId){
                $pingjunpaiming=$key+1;
                $pingjun = round($value['avg'],2);
            }
        }


        //胜率
        $arr6 = $qiuyou=RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
        $arr6= array_map('array_shift', $arr6);
        $arr6[] = $this->userId;
        $users6 = WebUserModel::whereIn('iSeqId', $arr4)
            ->orderBy("avg", "DESC")
            ->select(DB::raw('iAllWinPk/iAllPk as avg ,iSeqId'))
            ->get()
            ->toArray();
        $shenglvpaiming=0;
        $shenglv=0;
        foreach($users6 as $key => $value){
            if( $value['iSeqId'] == $this->userId){
                $shenglvpaiming=$key+1;
                $shenglv=$value['avg'];
            }
        }
        //qiuyoulv
        if(!empty($shenglvpaiming) && !empty($qiuyou)){
            $qiuyoulv=(count($qiuyou)-$shenglvpaiming+1)/count($qiuyou);
        }
        $data = [
            'uuid'          => $this->userId,
            'name'          => urldecode($user_data->sUserName),
            'image'         => $user_data->sUserImage,
            'clear_machine' => $user_data->iQinggan,//清台数
            'beat_rate'     => empty($qiuyoulv) ? 0 : $qiuyoulv,
            'sentiment_top' => array('sentiment'=>$renqi,'field_ranking'=>count($user1)==1? 0:$paiming,'count'=>count($user1)),
            'wealth_top'    => array('wealth'=>$caifu,'field_ranking'=>count($user2)==1? 0:$caifupaiming,'count'=>count($user2)),
            'winMoney_top'  => array('winMoney'=>$yingbi,'field_ranking'=>count($users3)==1? 0:$yingbipaiming,'count'=>count($users3)),
            'field_top'     => array('field_inof'=>$changci,'field_ranking'=>count($users4)==1? 0:$changcipaiming,'count'=>count($users4)),
            'avgtime_top'   => array('avgtime'=>$pingjun,'field_ranking'=>count($users5)==1? 0:$pingjunpaiming,'count'=>count($users5)),
            'odds_top'      => array('odds'=>$shenglv,'field_ranking'=>count($users6)==1? 0:$shenglvpaiming,'count'=>count($users6)),
        ];
        return response()->json(array('code' => 200,'message' => '信息查询成功','data'=>$data));
    }


    //我和对手的资料
    public function myFriend(Request $request){
        if ($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $user_data = WebUserModel::where('iUUID',$this->uuid)->first();
        $frienduuid = $request->input('frienduuid') ;
        if (!isset($frienduuid) || empty($frienduuid)) {
            return response()->json(array('code' => 400, 'message' => '对手uuid不能为空', 'data' => []));
        }
        $friend_data = WebUserModel::where('iUUID',$frienduuid)->first();
        if(empty($friend_data)){
            return response()->json(array('code' => 400, 'message' => '对手资料不存在', 'data' => []));
        }
        //好友的好友数量
        $arr1 = RelfriendModel::select("master_user_id")->where(array("master_user_id" => $friend_data->iSeqId))->count();

        //好友金币
        $arr2=GoldBeanModel::select("iNowGoldBean")->where(array("iUserId" => $friend_data->iSeqId))->first();

        /*$arr3=PkRelModel::where(array("master_userid"=>$this->userId,"userId"=>$friend_data->iSeqId,"iStatus"=>2))
            -> orWhereRaw("master_userid = {$friend_data->iSeqId} and userId = {$this->userId} and iStatus=2 ")
            //->groupBy('pkId')
            ->select(DB::raw('sum(iAll) as sumiAll'))
           ->first();*/
        //交战场次
        $arr3=PkRecordModel::where(array("iUserId"=>$this->userId,"iOpponentId"=>$friend_data->iSeqId,"iStatus"=>2))
            ->orWhereRaw("iUserId = {$friend_data->iSeqId} and iOpponentId = {$this->userId} and iStatus=2 ")
            ->get()
            ->toArray();

        //获胜场次
        $arr4=PkRelModel::where(array("master_userid"=>$this->userId,"userId"=>$friend_data->iSeqId,"iStatus"=>2,'iResult'=>1))
           // ->orWhere(array("userId"=>$friend_data->iSeqId,"master_userid"=>$this->userId,'iResult'=>1,"iStatus"=>2))
            ->get()
            ->toArray();

        //赢得金币


        $arr5=RelfriendModel::where(array("master_user_id" => $this->userId,"user_id"=>$friend_data->iSeqId))->first();

        //pk时长
        $arr6=PkRecordModel::where(array("iUserId"=>$this->userId,"iOpponentId"=>$friend_data->iSeqId,"iStatus"=>2))
            -> orWhereRaw("iUserId = {$friend_data->iSeqId} and iOpponentId = {$this->userId} and iStatus=2 ")
            ->select(DB::raw('sum(unix_timestamp(dtEndTime)-unix_timestamp(dtStartTime)) as pktime ,iSeqId'))
            ->get()
            ->toArray();

        //最近三场比赛
       /* $arr7=PkRecordModel::where(array("iUserId"=>$this->userId,"iOpponentId"=>$friend_data->iSeqId,"iStatus"=>2))
            -> Where(array("iUserIjd"=>$friend_data->iSeqId,"iOpponentId"=>$this->userId,"iStatus"=>2))
            ->orderBy("dtEndTime","DESC")
            ->limit(3)
            ->get()
            ->toArray();*/
        $arr7=PkRecordModel::where(array("iUserId"=>$this->userId,"iOpponentId"=>$friend_data->iSeqId,"iStatus"=>2))
            //-> orWhereRaw(array("iUserIjd"=>$friend_data->iSeqId,"iOpponentId"=>$this->userId,"iStatus"=>2))
            -> orWhereRaw("iUserId = {$friend_data->iSeqId} and iOpponentId = {$this->userId} and iStatus=2 ")
            ->orderBy("dtEndTime","DESC")
            ->limit(3)
            ->get()
            ->toArray();
        $sScore=[];
        //print_r($arr7);
        foreach($arr7 as $key=>$value){
            $sext=json_decode($value['sExt'],'true');
            if($value['iOpponentId']==$this->userId){
                $sScore[]=strrev($sext['sScore']);
            }else{
                $sScore[]=$sext['sScore'];
            }
        }

        $data = [
            "uuid"=>$this->uuid,
            'name' => urldecode($friend_data->sUserName),
            'image' => $friend_data->sUserImage,
            'fiend' => $arr1,
            'fiendGold' => empty($arr2) ? 0 : $arr2->iNowGoldBean,
            'pkchangci' =>  empty($arr3) ? 0 : count($arr3),
            'winchangci' =>  empty($arr4) ? 0 : count($arr4),
            'shenglv' => count($arr3)!=0 && count($arr4) !=0 ? count($arr4)/count($arr3) : 0,
            'wingold' =>empty($arr5->iAllReward) ? 0 :$arr5->iAllReward,
            'pktime' =>empty($arr6[0]['pktime']) ? 0 : $arr6[0]['pktime'],
            'lastthpk' =>$sScore,
        ];
        return response()->json(array('code' => 200,'message' => '查询成功','data'=>$data));
    }
}
